//import 'package:amap_base/amap_base.dart';

import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:flutter_bmfmap/BaiduMap/bmfmap_map.dart';
import 'package:flutter_bmfmap/BaiduMap/models/bmf_map_options.dart';
import 'package:flutter_hotwork/Myapplication.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/bean/DeviceBean.dart';
import 'package:flutter_hotwork/bean/ListDeviceForGisBean.dart';
import 'package:flutter_hotwork/bean/ProjectBean.dart';
import 'package:flutter_hotwork/bean/xunjian/guijilistbean.dart';
import 'package:flutter_hotwork/bean/xunjian/ticketslistbean.dart';
import 'package:flutter_hotwork/homepage/BaseTitleBar.dart';
import 'package:flutter_hotwork/homepage/BaseViewBar.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:flutter_hotwork/xunjiannew/XunJianArea.dart';

import '../Toast.dart';

class XunjianNewPage extends StatefulWidget {
  @override
  XunjianNewState createState() => new XunjianNewState();
}

Map<String, Object> _loationResult;
BaiduLocation _baiduLocation; // 定位结果
StreamSubscription<Map<String, Object>> _locationListener;
LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();
int firstlocation = 0;
Size screenSize;
Timer mtimer;
double latitude = MyApplication.bd_decrypt().latitude;
double longitude = MyApplication.bd_decrypt().longitude;
DeviceBean deviceBean;
ListDeviceForGisBean listDeviceForGisBean;
List<BMFCoordinate> coordinates = List();
List<BMFCoordinate> coordinatestickets = List();
var newtime = formatDate(
    new DateTime.now(), [yyyy, '-', mm, '-', dd, "  ", HH, ":", nn, ":", ss]);
guijilistbean guijilist;
ticketslistbean ticketslist;

int hasdata = 0;

class XunjianNewState extends State<XunjianNewPage> {
  XunjianNewState();

  BMFMapController myMapController;

  /// 纹理索引
  List<int> indexs = [0, 0, 0, 0];

  /// 纹理集合
  List<String> textures = List(4);

  @override
  void initState() {
    super.initState();
    DioUtils.createInstance();
  }

  @override
  void dispose() {
    hasdata = 0;
    firstlocation = 0;
    coordinates = List();
    coordinatestickets = List();
    if (null != _locationListener) {
      _locationListener.cancel(); // 停止定位
    }
    mtimer.cancel(); // 取消定时器
    super.dispose();
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(2000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType(
        "BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 启动定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _setLocOption();
      _locationPlugin.startLocation();
    }
  }

  /// 停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  /// 创建mapView回调
  BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(latitude, longitude),
      zoomLevel: 18,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

  /// 创建完成回调
  void onBMFMapCreated() {

    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });

    // /// 创建BMFMarker
    // BMFMarker marker = BMFMarker(
    //     position: BMFCoordinate(MyApplication.latitude, MyApplication.longitude),
    //     title: 'flutterMaker',
    //     identifier: 'flutter_marker',
    //     icon: 'images/icon_end.png');

    myMapController?.showUserLocation(true);

    BMFCoordinate coordinate = BMFCoordinate(latitude, longitude);

    BMFLocation location = BMFLocation(
        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);

    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );

    myMapController?.updateLocationData(userLocation);

    // BMFUserlocationDisplayParam displayParam = BMFUserlocationDisplayParam(
    //     locationViewOffsetX: 0,
    //     locationViewOffsetY: 0,
    //     accuracyCircleFillColor: Colors.red,
    //     accuracyCircleStrokeColor: Colors.blue,
    //     isAccuracyCircleShow: true,
    //     locationViewImage: 'images/weizhi.png',
    //     locationViewHierarchy:
    //     BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM);
    //
    // myMapController?.updateLocationViewWithParam(displayParam);
    /// 添加Marker
    // myMapController.addMarker(marker);

    // textures[0] = 'images/traffic_texture_smooth.png';
    // textures[1] = 'images/traffic_texture_slow.png';
    // textures[2] = 'images/traffic_texture_unknown.png';
    // textures[3] = 'images/traffic_texture_smooth.png';
    // /// 创建polyline
    // BMFPolyline texturesPolyline = BMFPolyline(
    //   // id: polylineOptions.hashCode.toString(),
    //     coordinates: coordinates,
    //     indexs: indexs,
    //     textures: textures,
    //     width: 16,
    //     dottedLine: true,
    //     lineDashType: BMFLineDashType.LineDashTypeNone,
    //     lineCapType: BMFLineCapType.LineCapButt,
    //     lineJoinType: BMFLineJoinType.LineJoinRound);
    //
    // /// 添加polyline
    // myMapController?.addPolyline(texturesPolyline);
    getDeviceList();
    queryProjectData();
  }

  //  扫描二维码

  @override
  Widget build(BuildContext context) {
    if (hasdata == 0) {
      _startLocation();
      if (_loationResult != null) {
        _loationResult.forEach((key, value) {
          if (key == "latitude") {
            latitude = value;
            MyApplication.latitude = value;
          }
          if (key == "locationDetail") {
            MyApplication.locationdetail = value;
          }
          if (key == "longitude") {
            longitude = value;
            MyApplication.longitude = value;
          }
        });
        if (MyApplication.nowtaskbean.taskStatus != 2) {
          if (null != latitude && null != longitude) {
            coordinates.add(BMFCoordinate(latitude, longitude));
            uploadxy(latitude, longitude);
          }
        }
      }
    }

    screenSize = MediaQuery.of(context).size;
    const timeout = const Duration(seconds: 5);
    if (firstlocation == 0 && MyApplication.nowtaskbean.taskStatus != 2) {
      /// 动态申请定位权限
      _locationPlugin.requestPermission();

      /// 设置ios端ak, android端ak可以直接在清单文件中配置
      LocationFlutterPlugin.setApiKey("AATp1fIh3jcs3nUN4wglXGzG209ZQZap");
      _locationListener = _locationPlugin
          .onResultCallback()
          .listen((Map<String, Object> result) {
        setState(() {
          _loationResult = result;
          try {
            _baiduLocation =
                BaiduLocation.fromMap(result); // 将原生端返回的定位结果信息存储在定位结果类中
//          print(_baiduLocation);
          } catch (e) {
            print(e);
          }
        });
      });
      firstlocation = 1;
      mtimer = new Timer.periodic(timeout, (mtimer) {
        //callback function
        //1s 回调一次
        if (hasdata <5) {
          _startLocation();
        }
        if (_loationResult != null) {
          _loationResult.forEach((key, value) {
            if (key == "latitude") {
              latitude = value;
              MyApplication.latitude = value;
            }
            if (key == "locationDetail") {
              MyApplication.locationdetail = value;
            }
            if (key == "longitude") {
              longitude = value;
              MyApplication.longitude = value;
            }
          });
          if (null != latitude && null != longitude) {
            coordinates.add(BMFCoordinate(latitude, longitude));
            uploadxy(latitude, longitude);
            onBMFMapCreated();
          }
        }
      });
    }

    return Scaffold(
        appBar: new BaseViewBar(
            childView: new BaseTitleBar(
              "智能巡检",
              leftIcon: 'images/fanhui.png',
              rightIcon: "",
              rightClick: () {
                // Navigator.push(context, MaterialPageRoute(builder: (context) {
                //   return new BasicLoc();
                // }));
              },
              leftClick: () {
                Navigator.of(context).pop();
                print("点击了左边干嘛啊。。。哦");
              },
            ),
            preferredSize: Size.fromHeight(50.0)),
        body: new SingleChildScrollView(
          child: new ConstrainedBox(
              constraints: new BoxConstraints(
                minHeight: 120.0,
              ),
              child: new Column(children: [
                Container(
                  height: MyApplication.nowtaskbean.taskStatus == 2
                      ? screenSize.height - 0
                      : screenSize.height - 160,
                  width: screenSize.width,
                  child: BMFMapWidget(
                    onBMFMapCreated: (controller) {
                      myMapController=controller;
                    },
                    mapOptions: mapOptions,
                  ),
                ),
                MyApplication.nowtaskbean.taskStatus == 2
                    ? Container()
                    : Column(children: [
                        Container(
                          margin: EdgeInsets.only(
                              left: 0, top: 5, right: 0, bottom: 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              // InkWell(
                              //   onTap: (){
                              //     Navigator.push(context, MaterialPageRoute(builder: (context) {
                              //       return new XunJianEditScreen();
                              //     }));
                              //   },
                              //   child:
                              //   Image(height:70,width: 70,image: AssetImage('images/wentishangbao.png')),
                              // ),

                              Container(
                                width: 20,
                              ),
                              InkWell(
                                onTap: () {
                                  Navigator.push(context,
                                      MaterialPageRoute(builder: (context) {
                                    return new XunJianAreaActivity();
                                  }));
                                },
                                child: Image(
                                    height: 70,
                                    width: 70,
                                    image: AssetImage('images/daka.png')),
                              ),

                              // Container(width: 20,),
                              // InkWell(
                              //   onTap: (){
                              //     Navigator.push(context, MaterialPageRoute(builder: (context) {
                              //       return new XunJianEndScreen();
                              //     }));
                              //   },
                              //   child:
                              //   Image(height:70,width: 70,image: AssetImage('images/jieshuxunjian.png')),
                              // )
                            ],
                          ),
                        )
                      ]),
              ])),
          // :Container()
        ));
  }

  BMFCoordinate bd_encrypt(double gg_lat, double gg_lon) {
    var X_PI = pi * 3000.0 / 180.0;
    double x = gg_lon, y = gg_lat;

    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * X_PI);

    double theta = atan2(y, x) + 0.000003 * cos(x * X_PI);

    double bd_lon = z * cos(theta) + 0.0065;

    double bd_lat = z * sin(theta) + 0.006;

    return new BMFCoordinate(bd_lat, bd_lon);
  }

//百度坐标转高德（传入经度、纬度）
  BMFCoordinate bd_decrypt(bd_lat, bd_lng) {
    var X_PI = pi * 3000.0 / 180.0;
    var x = bd_lng - 0.0065;
    var y = bd_lat - 0.006;
    var z = sqrt(x * x + y * y) - 0.00002 * sin(y * X_PI);
    var theta = atan2(y, x) - 0.000003 * cos(x * X_PI);
    var gg_lng = z * cos(theta);
    var gg_lat = z * sin(theta);
    return new BMFCoordinate(gg_lat, gg_lng);
  }

  // Future scan() async {
  //   try {
  //     // 此处为扫码结果，barcode为二维码的内容
  //     String barcode = await BarcodeScanner.scan();
  //     print('扫码结果: '+barcode);
  //     uploadticket(barcode);
  //   } on PlatformException catch (e) {
  //     if (e.code == BarcodeScanner.CameraAccessDenied) {
  //       // 未授予APP相机权限
  //       print('未授予APP相机权限');
  //     } else {
  //       // 扫码错误
  //       print('扫码错误: $e');
  //     }
  //   } on FormatException{
  //     // 进入扫码页面后未扫码就返回
  //     print('进入扫码页面后未扫码就返回');
  //   } catch (e) {
  //     // 扫码错误
  //     print('扫码错误: $e');
  //   }
  // }
  // //结束巡检
  // void uptask(var id,var status) async {
  //   var reqeuest =Map<Object,Object>();
  //   reqeuest["id"] = id;
  //   reqeuest["checkUser"] = MyApplication.loginuserinfo.userInfo.username;
  //   try {
  //     Response response;
  //     response = await DioUtils.dio.put(DioUtils.API_PREFIX+"/checkTask/overCheckTaskById", data: json.encode(reqeuest));
  //
  //     Map respMap = json.decode(response.data);
  //     basebean base = basebean.fromJson(respMap);
  //     print('响应数据：' + response.toString());
  //     if(base.code==0){
  //       LocalToast.toast(context,msg:"结束巡检成功！");
  //     }
  //   } catch (e) {
  //     LocalToast.toast(context,msg:"结束巡检失败！");
  //     print('请求出错：' + e.toString());
  //   }
  // }
  //实时上传轨迹
  void uploadxy(var latitude, var longitude) async {
    var reqeuest = Map<Object, Object>();

    print("定位经纬度:"+latitude.toString()+"--"+longitude.toString());
    // LocalToast.toast(context, msg:"经纬度:"+latitude.toString()+"--"+longitude.toString());
    reqeuest["lat"] = bd_decrypt(latitude, longitude).latitude;
    reqeuest["lon"] = bd_decrypt(latitude, longitude).longitude;
    reqeuest["inspectorId"] = MyApplication.nowtaskbean.getId();
    reqeuest["checkUser"] = MyApplication.loginuserinfo.userInfo.username;
    reqeuest["checkId"] = MyApplication.nowtaskbean.id;
    reqeuest["checkUserName"] = MyApplication.loginuserinfo.userInfo.realname;
    reqeuest["updateTime"] = formatDate(new DateTime.now(),
        [yyyy, '-', mm, '-', dd, "  ", HH, ":", nn, ":", ss]);
    // newtime=formatDate(new DateTime.now(),[yyyy,'-',mm,'-',dd ,"  ",HH,":",nn,":",ss]);
    try {
      Response response;
      response = await DioUtils.dio.post(
          DioUtils.API_PREFIX + "/checkTask/addGisInfo",
          data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      print('响应定位成功：' + response.toString());
      setState(() {});
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }

  //上传打卡点
  // void uploadticket(var clockInNumber) async {
  //   showDialog(
  //       context: context,
  //       builder: (context) {
  //         return new LoadingDialog();
  //       });
  //   var reqeuest =Map<Object,Object>();
  //   reqeuest["lat"] = bd_decrypt(latitude,longitude).latitude;
  //   reqeuest["lon"] = bd_decrypt(latitude,longitude).longitude;
  //   reqeuest["clockInNumber"] = clockInNumber;
  //   reqeuest["checkId"] = MyApplication.nowtaskbean.id;
  //   reqeuest["clockTime"] = new DateTime.now().toString();
  //   try {
  //     Response response;
  //     response = await DioUtils.dio.post(DioUtils.API_PREFIX+"/clockIn/insertClockIn", data: json.encode(reqeuest));
  //
  //     Map respMap = json.decode(response.data);
  //     basebean base = basebean.fromJson(respMap);
  //     Navigator.pop(context);
  //     if(base.code==0){
  //       coordinatestickets.add(BMFCoordinate(latitude, longitude));
  //       LocalToast.toast(context,msg: "打卡成功");
  //       setState(() {
  //         BMFMarker marker = BMFMarker(
  //             position: BMFCoordinate(latitude, longitude),
  //             title: '打卡',
  //             identifier: '打卡',
  //             icon: 'images/takepoint.png')
  //         ;
  //         myMapController.addMarker(marker);
  //
  //       });
  //     }
  //     print('响应数据：' + response.toString());
  //   } catch (e) {
  //     Navigator.pop(context);
  //     LocalToast.toast(context,msg: "打卡失败");
  //   }
  // }

  //获取设备类型显示
  void listDeviceForGis() async {
    try {
      Response response;
      response = await DioUtils.dio
          .get(DioUtils.API_PREFIX + "/checkDevice/listDeviceForGis");
      Map respMap = json.decode(response.data);
      listDeviceForGisBean = ListDeviceForGisBean.fromJson(respMap);
      print('请求出错22：' + response.toString());
      // List<BMFMarker> markers = new List();
      // for (int i = 0; i < 1; i++) {
      /// 创建BMFMarker
      BMFMarker marker = BMFMarker(
          position: BMFCoordinate(39.928617, 116.40329),
          title: '设备',
          identifier: '设备',
          icon: 'images/device.png');
      // markers.add(marker);
      // }
      myMapController?.addMarker(marker);
    } catch (e) {
      print('请求出错22：' + e.toString());
    }
  }

  //获取区域
  void queryProjectData() async {
    // Navigator.pop(context);
    try {
      Response response;
      response = await DioUtils.dio.get(
          DioUtils.API_PREFIX + "/checkProjectResult/listCheckProjectResult");
      Map respMap = json.decode(response.data);
      MyApplication.projectBean = ProjectBean.fromJson(respMap);
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }

  //获取设备点
  void getDeviceList() async {
    // Navigator.pop(context);
    try {
      Response response;
      response = await DioUtils.dio.get(DioUtils.API_PREFIX +
          "/checkTask/getAppCheckTask?checkUser=" +
          MyApplication.loginuserinfo.userInfo.username +
          "&taskId=" +
          MyApplication.nowtaskbean.id.toString());
      Map respMap = json.decode(response.data);
      deviceBean = DeviceBean.fromJson(respMap);
      hasdata += 1;
      for (int i = 0; i < deviceBean.result.length; i++) {
        double la = double.parse(deviceBean.result[i].deviceLonglat
            .substring(0, deviceBean.result[i].deviceLonglat.indexOf(",")));
        double long = double.parse(deviceBean.result[i].deviceLonglat.substring(
            deviceBean.result[i].deviceLonglat.indexOf(",") + 1,
            deviceBean.result[i].deviceLonglat.length));
        coordinatestickets.add(bd_encrypt(long, la));
      }
      List<BMFMarker> markers = new List();
      for (int i = 0; i < coordinatestickets.length; i++) {
        /// 创建BMFMarker
        BMFMarker marker = BMFMarker(
            position: coordinatestickets[i],
            title: '设备',
            identifier: '设备',
            icon: 'images/famen.png');
        markers.add(marker);
      }
      setState(() {
        myMapController.addMarkers(markers);
      });
    } catch (e) {
      print('请求出错：' + e.toString());
    }
  }
}
